package com.dsr.service.impl;

import cn.hutool.core.date.DateTime;
import com.dsr.bean.CollectTopBean;
import com.dsr.consts.Result;
import com.dsr.consts.e.UserProperty;
import com.dsr.dao.CollectDao;
import com.dsr.dao.FlowerDao;
import com.dsr.entity.Collect;
import com.dsr.entity.Flower;
import com.dsr.exception.FlowerException;
import com.dsr.service.CollectService;
import com.dsr.util.BasicUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationExpression;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.bson.Document;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * (Collect)表服务实现类
 *
 * @author dsr
 * @since 2020-10-07
 */
@Service("collectService")
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectDao collectDao;
    @Autowired
    private FlowerDao flowerDao;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Result getEntity(String flowerId) {
        Collect collect = collectDao.findByFlowerIdAndUserId(flowerId, BasicUtil.getToken(UserProperty.USER_ID));
        if(collect!=null){
            return Result.success(true);
        }
        return Result.success(false);
    }


    @Override
    public Result save(Collect collect) {
        collect.setCreateDate(DateTime.now());
        String userId = BasicUtil.getToken(UserProperty.USER_ID);
        if(StringUtils.isEmpty(userId)){
            throw new FlowerException(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,"登录失效");
        }
        collect.setUserId(userId);
        collectDao.insert(collect);
        return Result.success("收藏成功");
    }


    @Override
    public Result delete(String flowerId) {
        if (StringUtils.isNotEmpty(flowerId)) {
            collectDao.deleteByFlowerIdAndUserId(flowerId,BasicUtil.getToken(UserProperty.USER_ID));
            return Result.success("取消成功");
        }
        return Result.error("请选择取消的产品");
    }

    @Override
    public Result list() {
        String userId = BasicUtil.getToken(UserProperty.USER_ID);
        if(StringUtils.isEmpty(userId)){
            throw new FlowerException(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,"登录失效");
        }
        List<Collect> collectList = collectDao.findByUserId(userId);
        if(collectList.size()==0){
            return Result.success(null);
        }else {
            List<String> flowerIds = collectList.stream().map(Collect::getFlowerId).collect(Collectors.toList());
            Example example = new Example(Flower.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id",flowerIds);
            return Result.success(flowerDao.selectByExample(example));
        }

    }
    @Override
    public Result collectTop() {
        Sort.Order order = Sort.Order.desc("num");
        Sort sort = Sort.by(order);
        TypedAggregation<Collect> agg = Aggregation.newAggregation(Collect.class,
                Aggregation.group("flowerId").count().as("num"),
                Aggregation.limit(6),
                Aggregation.sort(sort)
        );
        AggregationResults<Document> result = mongoTemplate.aggregate(agg,Document.class);
        List<String> id = new ArrayList<>();
        for (Document item : result.getMappedResults()) {
            Object o = item.get("_id");
            id.add(o.toString());
        }
        List<Flower> flowers = flowerDao.selectIdIn(id);

        List<CollectTopBean> collectList=new ArrayList<>();
        result.getMappedResults().forEach(item->{
            CollectTopBean collectTopBean = new CollectTopBean();
            collectTopBean.setNum(Integer.parseInt(item.get("num").toString()));
            String flowerId=item.get("_id").toString();
            for (Flower flower : flowers) {
                if(flower.getId().equals(flowerId)){
                    collectTopBean.setTitle(flower.getTitle());
                    collectTopBean.setPrice(flower.getPrice());
                    flowers.remove(item);
                    collectList.add(collectTopBean);
                    break;
                }
            }
        });
        return Result.success(collectList);
    }

}